local mis_uu       = require('modules.commhm.utils')
local mis_config   = require('mis_config');
local mis_rank     = require('mis_rank')
local log       = require("modules.commhm.log");
local mis_data     = nil
local mis_log      = nil
local mis_bridge   = nil
local t_retCode    = nil


local ngx = ngx
local pairs = pairs
local table = table
local math = math
local math_max = math.max
local math_min = math.min
local tonumber = tonumber
local tostring = tostring
local table_insert = table.insert


-- 觉醒活动
local this = {
	s_name = string.match(debug.getinfo(1).short_src, '.*/(.*).lua');	-- 模块名称
}


this.log = function (msg)
	mis_log.day(this.s_name, msg)
end


local get_map_ranking = function (s_mapID)
	return mis_rank.instance('boat_festival_' .. s_mapID)
end


this.get_rank_top = function ()
	local t_params = ngx.ctx.t_params
	local n_uin    = t_params.uin
	local s_mapID  = tonumber(t_params.mapId)
	local version  = t_params.rank_ver
	local n_page   = tonumber(t_params.page) or 1
	local s_type = "boat_festival"

	local ranking = get_map_ranking(s_mapID)
	if not ranking then
		return t_retCode.n_WORK_ERR, 'rank instance not found'
	end

	-- 角色自身缓存数据 
	local t_user = mis_data.get_user()
	local n_code, t_userData = t_user:get_share_mission_data(s_type, true)
	if n_code ~= t_retCode.n_OK then
		return n_code, 'get user data error'
	end

	t_userData.map = t_userData.map or {}
	t_userData.map[s_mapID] = t_userData.map[s_mapID] or {}

	-- 组装消息数据
	local t_rankTop = ranking:Get() or {}
	local n_pageCnt = version and version ~= t_rankTop.version and 1 or n_page
	local rsp = {
		rank    = {},                 -- 一页榜单数据
		page    = n_pageCnt,		  -- 当前是第几页
		total   = t_rankTop.total,    -- 可展示榜单数
		version = t_rankTop.version,  -- 榜单版本信息
		self    = {                   -- 自己的排名信息
			rank  = -1,             -- 不在前100名榜单内
			value = t_userData.map[s_mapID].rankValue or 0
		}
	}
	-- 每页返回20个玩家数据
	local start = (n_pageCnt - 1) * 100 + 1
	local final =  n_pageCnt * 100
	for top, role in pairs(t_rankTop.rank or {}) do
		if top >= start and top <= final then
			rsp.rank[top] = role
		end
		if tonumber(role.uid) == n_uin then
			rsp.self.rank  = top
			rsp.self.value = role.value
		end
	end

	return t_retCode.n_OK, rsp
end


local update_role_map_value = function (t_user, t_userData, t_rankConf, s_mapID, n_value)
	-- 角色自身缓存数据
	local s_type = "boat_festival"
	t_userData.map = t_userData.map or {}
	t_userData.map[s_mapID] = t_userData.map[s_mapID] or {}
	-- TODO: 这块的逻辑应该挪入排汗榜模块内
	if t_rankConf.updates == mis_rank.Updates.FullVolume then
		if t_rankConf.order_by == mis_rank.OrderBy.ASC then
			local rankValue = tonumber(t_userData.map[s_mapID].rankValue)
			t_userData.map[s_mapID].rankValue = not rankValue and n_value or math_min(n_value, rankValue)
		else
			local rankValue = tonumber(t_userData.map[s_mapID].rankValue) or 0
			t_userData.map[s_mapID].rankValue = math_max(n_value, rankValue)
		end
	else
		t_userData.map[s_mapID].rankValue = t_userData.map[s_mapID].rankValue or 0
		t_userData.map[s_mapID].rankValue = t_userData.map[s_mapID].rankValue + n_value
	end
	local n_code, s_desc = t_user:set_share_mission_data(s_type, t_userData)
	if n_code ~= t_retCode.n_OK then
		return n_code, s_desc
	end
	log.loggerdebug("==t_userData : %%", t_userData)
	return t_retCode.n_OK
end


this.update_rank = function ()
	local t_params   = ngx.ctx.t_params
	local n_uin      = t_params.uin
	local n_updates  = t_params.updates
	local s_mapID    = tonumber(t_params.mapId)
	local n_value    = tonumber(t_params.value)

	if not n_value then
		return t_retCode.n_PARAM_ERR
	end

	local s_type = "boat_festival"
	local t_Config = mis_data.t_share_mission[s_type] or {}
	-- 榜单配置
	local t_rankConf = t_Config.t_conf.t_rank[s_mapID] or {}
	if mis_uu.tableIsEmpty(t_rankConf) then
		return t_retCode.n_OPER_ERR, 'no rank conf'
	end
	if n_updates ~= t_rankConf.updates then
		return t_retCode.n_OPER_ERR, 'invalid updates'
	end
	if t_rankConf.limit_min and n_value < t_rankConf.limit_min then
		return t_retCode.n_OPER_ERR, 'invalid value min'
	end
	if t_rankConf.limit_max and n_value > t_rankConf.limit_max then
		return t_retCode.n_OPER_ERR, 'invalid value min'
	end

	local n_code, s_desc, t_userData
	local t_user = mis_data.get_user()
	n_code, t_userData = t_user:get_share_mission_data(s_type)
	if n_code ~= t_retCode.n_OK then
		return n_code, 'get user data error'
	end

	n_code, s_desc = update_role_map_value(t_user, t_userData, t_rankConf, s_mapID, n_value)
	if n_code ~= t_retCode.n_OK then
		return n_code, s_desc
	end

	local t_profile = {
		rolename  = t_params.rolename,
		portrait  = t_params.portrait,
		headframe = t_params.headframe,
	}
	local ranking = get_map_ranking(s_mapID)
	if not ranking or not ranking:Set( n_uin, t_userData.map[s_mapID].rankValue, t_profile ) then
		return t_retCode.n_PARAM_ERR, "set rank err"
	end

	return t_retCode.n_OK
end


local add_friend = function (src_uin, dst_uin)
	if tonumber(ngx.ctx.t_params.add_friend) ~= 1 then
		return
	end
	local n_code, s_desc = mis_bridge.apply_friend(src_uin, dst_uin, 0)
	if n_code ~= t_retCode.n_OK then
		this.log( 'code_exchange make friend fault' .. mis_uu.to_str({
			src_uin = src_uin,
			dst_uin = dst_uin,
			code = n_code,
			message = s_desc
		}))
	end
end


-- 兑换码结束后额外处理
this.share_mission_code_exchagne = function (t_user, t_userData, t_codeData, t_callbackData, rsp)
	-- 使用兑换码后加为好友
	local s_type = "boat_festival"
	local task = t_userData.tasks or {}
	local k_list = {}
	for k, v in pairs(task.boat_festival or 0) do
		if v.event == 28 and v.status == 1 then  --自动领取奖励
			k_list[#k_list+1] = k
		end
	end

	if next(k_list) then
		local t_Config = mis_data.t_share_mission[s_type] or {}
		local t_conf = t_Config.t_conf
		if not (t_conf and t_conf.t_mission ) then
			return t_retCode.n_PARAM_ERR, 'config error'
		end

		for _, index in pairs(k_list) do
			local items = {}
			for _, _cfg in pairs(t_conf.t_mission[28]or {}) do
				if _cfg.n_subTaskId == index then
					items = _cfg.t_bonus
					break
				end
			end
			for k, item in pairs(items) do
				if item.s_itemId == "mis_item_3" then
					t_userData.exchange_num= (t_userData.exchange_num or 0) + item.n_num
					rsp.award_num = (rsp.award_num or 0) + item.n_num
				end
			end
			t_userData.tasks.boat_festival[index].status = 2
			add_friend(t_user.n_uin, t_codeData.uin)
		end
	end
end


-- 绑定手机领取奖励
this.bind_phone_rewards = function (t_user, t_userData, phone_config, t_resp, s_type)
	local n_code, s_desc
	local uin = ngx.ctx.t_params.uin
	--检查是否绑定手机
	if not mis_bridge.query_bind_phone(uin) then
		return t_retCode.n_NO_DATA, "not bind phone"
	end
	t_userData.phone_data = t_userData.phone_data or {}
	if t_userData.phone_data.had_pick then
		return t_retCode.n_WORK_ERR, "had pick"
	end

	t_userData.exchange_num = (t_userData.exchange_num or 0) + phone_config.rewards.num
	t_userData.phone_data.had_pick = 1

	t_resp.award_num = t_userData.exchange_num

	n_code, s_desc = t_user:set_share_mission_data(s_type, t_userData)
	if n_code ~= t_retCode.n_OK then
		return n_code, s_desc
	end

	return t_retCode.n_OK
end


-- 获取活动主页数据
this.share_mission_status = function ( t_user, t_userData, t_award, t_resp, n_exchangeType )
	t_userData.phone_data = t_userData.phone_data or {}
	t_resp.pick_phone_rewards = t_userData.phone_data.had_pick or 0

	return t_retCode.n_OK
end

-- 说明：模块包含
-- 参数：模块表
this.modules_include = function(t_moddules)
	mis_data     = t_moddules.mis_data
	mis_log      = t_moddules.mis_log
	mis_bridge   = t_moddules.mis_bridge
	mis_config   = t_moddules.mis_config
	t_retCode    = mis_config.t_retCode
end


return this

